package seatiger.tomcat.util.net;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 对SocketChannel的封装，怎么分配ByteBuffer,怎么读写数据
 *
 */
public class NioChannel {

    protected SocketChannel sc = null;

    protected ApplicationBufferHandler bufHandler;

    protected NioEndpoint.Poller poller;

    public NioChannel(SocketChannel channel, ApplicationBufferHandler bufHandler) throws IOException {
        this.sc = channel;
        this.bufHandler = bufHandler;
    }

    public ApplicationBufferHandler getBufHandler() {
        return bufHandler;
    }

    /**
     * 怎么分配ByteBuffer
     */
    public interface ApplicationBufferHandler {
        ByteBuffer getReadBuffer();
        ByteBuffer getWriteBuffer();
    }

    /**
     * 写出数据
     * @param src
     */
    public int write(ByteBuffer src) throws IOException{
        return sc.write(src);
    }

    /**
     * 读数据
     * @param dst
     * @throws IOException
     */
    public int read(ByteBuffer dst) throws IOException{
        return sc.read(dst);
    }

    public SocketChannel getIOChannel() {
        return sc;
    }

    public void setPoller(NioEndpoint.Poller poller) {
        this.poller = poller;
    }

    public NioEndpoint.Poller getPoller() {
        return poller;
    }
}
